package com.app.studyroom;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.studyroom.dialog.CustomSizeDialog;
import com.app.studyroom.peripherals.icCardRead.CardReaderGuard;

import java.util.concurrent.Executors;

/** 门禁页面：刷 IC 卡 / 人脸识别 开门 */
public class AccessControlActivity extends BaseActivity {

    /* UI */
    private Button   btnICAccess, btnFaceAccess;
    private ImageView btnBack;

    /* Dialog 引用 */
    private CustomSizeDialog currentCardDialog;
    private TextView  tvCardStatus;
    private ImageView imgCardAnim;

    /* ───────── 生命周期 ───────── */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_access_control);

        btnBack       = findViewById(R.id.ic_back);
        btnICAccess   = findViewById(R.id.btnICAccess);
        btnFaceAccess = findViewById(R.id.btnFaceAccess);

        btnBack.setOnClickListener(v -> onBackPressed());
        btnICAccess.setOnClickListener(v -> showICCardDialog());
        btnFaceAccess.setOnClickListener(v -> startFaceAccess());
    }

    /* ───────── 弹出刷卡 Dialog ───────── */
    private void showICCardDialog() {
        CardReaderGuard.isReadingCard = true;                // 放行数字/Enter

        currentCardDialog = new CustomSizeDialog(
                this, R.layout.dialog_ic_card_access, 0.7f, 0.65f);
        currentCardDialog.show();

        imgCardAnim = currentCardDialog.findViewById(R.id.door_access);
        tvCardStatus= currentCardDialog.findViewById(R.id.tvCardStatus);

        //禁用键盘 不弹出
        TextView tvCardId = currentCardDialog.findViewById(R.id.tvCardId);
        EditText etInput = currentCardDialog.findViewById(R.id.etCardInput);
        etInput.setInputType(android.text.InputType.TYPE_NULL);
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            etInput.setShowSoftInputOnFocus(false);
        }

        etInput.requestFocus();                              // 接 HID 输入

        etInput.setOnKeyListener((v, keyCode, ev) -> {
            if (ev.getAction() == KeyEvent.ACTION_DOWN &&
                    (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) {

                String cardId = etInput.getText().toString().trim();
                Toast.makeText(this, "读取到卡号: " + cardId, Toast.LENGTH_SHORT).show();
                tvCardStatus.setText("验证中…");
                tvCardId.setText(cardId);                    // ★ 显示到 TextView
                checkPermissionAsync(cardId);                // ► 后台校验
                return true;
            }
            return false;
        });
    }

    /* ───────── 后台权限校验 ───────── */
    private void checkPermissionAsync(String cardId) {
        Executors.newSingleThreadExecutor().execute(() -> {
            boolean ok = verifyPermissionWithBackend("IC_CARD", cardId);
            runOnUiThread(() -> showVerifyResult(ok));
        });
    }

    /* ───────── 校验完后 UI 反馈 + 跳转 ───────── */
    private void showVerifyResult(boolean ok) {
        if (currentCardDialog == null) return;

        tvCardStatus.setText(ok ? "验证成功，门已开" : "验证失败，拒绝开门");

        /* 150 ms 淡出 Dialog，再跳首页 */
        currentCardDialog.getWindow().getDecorView()
                .animate()
                .alpha(0f)
                .setDuration(150)
                .withEndAction(() -> finishFlow(ok))
                .start();
    }

    private void finishFlow(boolean ok) {
        if (currentCardDialog != null) currentCardDialog.dismiss();
        currentCardDialog = null;
        CardReaderGuard.isReadingCard = false;               // 退出刷卡模式

        if (ok) {
            Intent home = new Intent(this, HomeActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(home);
            overridePendingTransition(android.R.anim.fade_in,
                    android.R.anim.fade_out);
        }
    }

    /* ───────── 人脸识别入口 ───────── */
    private void startFaceAccess() {
        String faceId = recognizeFace();
        boolean ok = verifyPermissionWithBackend("FACE_ID", faceId);
        Toast.makeText(this, ok ? "门禁已打开" : "无权限，请联系管理员", Toast.LENGTH_SHORT).show();
        if (ok) {
            Intent home = new Intent(this, HomeActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(home);
            overridePendingTransition(android.R.anim.fade_in,
                    android.R.anim.fade_out);
            finish();
        }
    }

    /* ───────── 占位业务方法 ───────── */
    private boolean verifyPermissionWithBackend(String type, String id) { return true; }
    private String  recognizeFace() { return "FACE987654321"; }

    /* HOME / BACKGROUND 时兜底复位 */
    @Override protected void onPause() {
        super.onPause();
        CardReaderGuard.isReadingCard = false;
    }
}
